// 确保在DOM加载完成后执行Vue应用初始化
document.addEventListener('DOMContentLoaded', function() {
    const { createApp, ref, onMounted } = Vue;

    const app = createApp({
    setup() {
        // 响应式数据
        const categoryName = ref('');
        const categories = ref([]);
        const loading = ref(false);
        const errorMessage = ref('');
        const showError = ref(false);
        const successMessage = ref('');
        const showSuccess = ref(false);
        const selectedCategories = ref([]);
        const searchQuery = ref('');
        const name = ref('');
        const desc = ref('');

        // 加载分类列表
        const loadCategories = () => {
            loading.value = true;
            showError.value = false;
            showSuccess.value = false;
            
            fetch('/get_category')
                .then(response => response.json())
                .then(data => {
                    loading.value = false;
                    if (data.success && data.category_list) {
                        categories.value = data.category_list;
                        // 计算每个分类的文档数量
                        categories.value.forEach(category => {
                            category.documentCount = category.documents?.length || 0;
                        });
                    } else {
                        errorMessage.value = data.message || '加载分类列表失败';
                        showError.value = true;
                    }
                })
                .catch(error => {
                    loading.value = false;
                    errorMessage.value = error.message || '加载分类列表失败';
                    showError.value = true;
                    console.error('加载分类列表失败:', error);
                });
        };

        // 表单提交处理函数
        const handleAddCategory = (event) => {
            event.preventDefault();
            addCategory();
        };

        // 添加新分类
        const addCategory = () => {
            if (!name.value.trim()) {
                errorMessage.value = '请输入分类名称';
                showError.value = true;
                return;
            }

            loading.value = true;
            showError.value = false;
            showSuccess.value = false;

            const categoryData = {
                name: name.value.trim(),
                desc: desc.value.trim()
            };

            fetch('/add_category', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(categoryData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.detail || errorData.message || `HTTP错误: ${response.status} ${response.statusText}`);
                    }).catch(() => {
                        throw new Error(`网络响应错误: ${response.status} ${response.statusText}`);
                    });
                }
                return response.json();
            })
            .then(data => {
                loading.value = false;
                if (data.success) {
                    categoryName.value = '';
                    successMessage.value = '分类添加成功';
                    showSuccess.value = true;
                    loadCategories(); // 重新加载分类列表
                    
                    // 3秒后自动隐藏成功消息
                    setTimeout(() => {
                        showSuccess.value = false;
                    }, 3000);
                } else {
                    errorMessage.value = data.message || '添加分类失败';
                    showError.value = true;
                }
            })
            .catch(error => {
                loading.value = false;
                errorMessage.value = error.message || '添加分类过程中发生错误';
                showError.value = true;
                console.error('添加分类错误:', error);
            });
        };

        // 删除分类
        const deleteCategory = (categoryName) => {
            if (!confirm(`确定要删除分类 "${categoryName}" 吗？这将同时删除该分类下的所有文档。`)) {
                return;
            }

            loading.value = true;
            showError.value = false;
            showSuccess.value = false;

            const categoryData = {
                category_name: categoryName
            };

            fetch('/delete_category', {
                method: 'DELETE',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(categoryData)
            })
            .then(response => {
                if (!response.ok) {
                    return response.json().then(errorData => {
                        throw new Error(errorData.detail || errorData.message || `HTTP错误: ${response.status} ${response.statusText}`);
                    }).catch(() => {
                        throw new Error(`网络响应错误: ${response.status} ${response.statusText}`);
                    });
                }
                return response.json();
            })
            .then(data => {
                loading.value = false;
                if (data.success) {
                    successMessage.value = '分类删除成功';
                    showSuccess.value = true;
                    loadCategories(); // 重新加载分类列表
                    
                    // 3秒后自动隐藏成功消息
                    setTimeout(() => {
                        showSuccess.value = false;
                    }, 3000);
                } else {
                    errorMessage.value = data.message || '删除分类失败';
                    showError.value = true;
                }
            })
            .catch(error => {
                loading.value = false;
                errorMessage.value = error.message || '删除分类过程中发生错误';
                showError.value = true;
                console.error('删除分类错误:', error);
            });
        };

        // 切换分类选择状态
        const toggleCategorySelection = (categoryName) => {
            const index = selectedCategories.value.indexOf(categoryName);
            if (index > -1) {
                selectedCategories.value.splice(index, 1);
            } else {
                selectedCategories.value.push(categoryName);
            }
        };

        // 检查分类是否被选中
        const isCategorySelected = (categoryName) => {
            return selectedCategories.value.includes(categoryName);
        };

        // 检查是否所有分类都被选中
        const isAllSelected = () => {
            if (categories.value.length === 0) return false;
            return categories.value.every(category => 
                selectedCategories.value.includes(category.name)
            );
        };

        // 切换全选/取消全选
        const toggleSelectAll = () => {
            if (isAllSelected()) {
                selectedCategories.value = [];
            } else {
                selectedCategories.value = categories.value.map(category => category.name);
            }
        };

        // 处理删除按钮点击事件
        const handleDeleteCategory = () => {
            batchDeleteCategories();
        };

        // 批量删除选中的分类
        const batchDeleteCategories = () => {
            if (selectedCategories.value.length === 0) {
                errorMessage.value = '请先选择要删除的分类';
                showError.value = true;
                return;
            }

            if (!confirm(`确定要删除选中的 ${selectedCategories.value.length} 个分类吗？这将同时删除这些分类下的所有文档。`)) {
                return;
            }

            loading.value = true;
            showError.value = false;
            showSuccess.value = false;

            // 依次删除每个选中的分类
            let deleteCount = 0;
            const totalToDelete = selectedCategories.value.length;
            const deletedCategories = [...selectedCategories.value];
            selectedCategories.value = [];

            const deleteNextCategory = (categoryIndex) => {
                if (categoryIndex >= totalToDelete) {
                    loading.value = false;
                    successMessage.value = `成功删除 ${deleteCount} 个分类`;
                    showSuccess.value = true;
                    loadCategories(); // 重新加载分类列表
                    
                    // 3秒后自动隐藏成功消息
                    setTimeout(() => {
                        showSuccess.value = false;
                    }, 3000);
                    return;
                }

                const categoryName = deletedCategories[categoryIndex];
                const categoryData = {
                    category_name: categoryName
                };

                fetch('/delete_category', {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(categoryData)
                })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`删除分类 ${categoryName} 失败`);
                    }
                    return response.json();
                })
                .then(data => {
                    if (data.success) {
                        deleteCount++;
                    }
                    deleteNextCategory(categoryIndex + 1);
                })
                .catch(error => {
                    console.error(`删除分类 ${categoryName} 错误:`, error);
                    deleteNextCategory(categoryIndex + 1);
                });
            };

            deleteNextCategory(0);
        };

        // 导出分类模板
        const exportCategoryTemplate = () => {
            const templateData = {
                categories: categories.value
            };
            
            const blob = new Blob([JSON.stringify(templateData, null, 2)], { type: 'application/json' });
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = `categories_template_${new Date().toISOString().split('T')[0]}.json`;
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            URL.revokeObjectURL(url);
        };

        // 关闭错误消息
        const closeError = () => {
            showError.value = false;
        };

        // 添加导航栏滚动效果
        const setupScrollEffects = () => {
            const navbar = document.querySelector('nav');
            if (!navbar) return;

            window.addEventListener('scroll', function() {
                if (window.scrollY > 10) {
                    navbar.classList.add('bg-white/95', 'backdrop-blur-sm');
                } else {
                    navbar.classList.remove('bg-white/95', 'backdrop-blur-sm');
                }
            });
        };

        // 页面加载完成后初始化
        onMounted(() => {
            loadCategories();
            setupScrollEffects();

            // 平滑滚动效果
            document.querySelectorAll('a[href^="#"]').forEach(anchor => {
                anchor.addEventListener('click', function (e) {
                    e.preventDefault();
                    document.querySelector(this.getAttribute('href'))?.scrollIntoView({
                        behavior: 'smooth'
                    });
                });
            });
        });

        // 导出供模板使用的数据和方法
        return {
            categoryName,
            categories,
            loading,
            errorMessage,
            showError,
            successMessage,
            showSuccess,
            selectedCategories,
            searchQuery,
            name,
            desc,
            addCategory,
            deleteCategory,
            handleDeleteCategory,
            toggleCategorySelection,
            isCategorySelected,
            isAllSelected,
            toggleSelectAll,
            batchDeleteCategories,
            exportCategoryTemplate,
            handleAddCategory,
            closeError
        };
    }
    });

    app.mount('#app');
});